#!/usr/bin/env bash
#
# Copyright 2016-2018 Axel Huebl
#
# This file is part of PIConGPU.
#
# PIConGPU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# PIConGPU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PIConGPU.
# If not, see <http://www.gnu.org/licenses/>.
#

# Search recursive inside our C++ source files if they violate our coding
# style by using a wrong pre-compiler spacing style.
# See:
#   https://github.com/ComputationalRadiationPhysics/contributing/blob/master/codingGuideLines/cpp.md#7-preprocessor
#
# @result 0 if no files with tabs are found, else 1
#

ok=0
files=()

# only C++ files
pattern="\.def$|\.h$|\.cpp$|\.cu$|\.hpp$|\.tpp$|\.kernel$|\.loader$|"\
"\.param$|\.unitless$|\.conf$"

for i in $(find . \
                -not -path "./.git/*" \
                -not -path "./thirdParty/*" \
                -type f | \
           grep -P "${pattern}")
do
  result=$(grep --color='always' -n -P "^\s+\#(?!pragma)" $i)

  if [ $? -eq 0 ]
  then
    files+=($i)
    echo "$i contains spaces before '#' pre-compiler commands in C++ files!"
    echo "$result"
    ok=1
  fi
done

if [ $ok -ne 0 ]
then
  echo ""
  echo "SUMMARY"
  echo "-------"
  echo "Run the following command(s) on the above files to update your style:"
  echo ""
  for i in ${files[@]}
  do
    #             exclude "#pragma" lines, since most are not pre-compiler macros,
    #             by jumping to the end of the sed script when found
    #             |        |
    #             |        |  swap "[spaces]#"           |
    #             v        v  v                          v
    echo "sed -i '/#pragma/b; s/^\([[:blank:]]\+\)\#/\#\1/' $i"
  done
fi

exit $ok
